import axios from "axios";
import { ElMessage } from "element-plus";

class HYRequest {
  instance;
  interceptors;

  constructor(config) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    // 实例私有的拦截器，个性化配置
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    /**
     * 添加所有实例里都有的拦截器
     * 请求拦截器：后添加的先执行
     * 响应拦截器：后添加的后执行
     */
    this.instance.interceptors.request.use(
      (config) => {
        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );

    this.instance.interceptors.response.use(
      (resOrign) => {
        const res = resOrign.data;
        return res;
      },
      (err) => {
        ElMessage({
          message: err.message,
          type: "error",
          duration: 5 * 1000,
        });
        return Promise.reject(err);
      }
    );
  }

  /**
   * 指定返回的promise的结构可以由调用request时指定
   */
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
          return err;
        });
    });
  }
}

export default HYRequest;
